﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Text.RegularExpressions;

namespace Valentia.Kinection.Service.Manager
{
    /// <summary>
    /// This form is used to view and update the Service Manager application settings
    /// </summary>
    public partial class ServiceManagerSettings : Form
    {
        #region Constructor

        /// <summary>
        /// Constructor. [Can throw exception]
        /// </summary>
        public ServiceManagerSettings()
        {
            InitializeComponent();

            // Postioning the form in the center of the screen
            this.StartPosition = FormStartPosition.CenterScreen;

            LoadSettings();
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// This method is used to load service manager application settings
        /// </summary>
        private void LoadSettings()
        {
            try
            {
                this.txtClientName.Text = System.Configuration.ConfigurationSettings.AppSettings["ClientName"];
                this.txtLoginName.Text = System.Configuration.ConfigurationSettings.AppSettings["LoginName"];
                this.txtPassword.Text = System.Configuration.ConfigurationSettings.AppSettings["Password"];
                this.txtServerURI.Text = System.Configuration.ConfigurationSettings.AppSettings["ServerURI"];
                numConnectionPort.Value = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["ServerPort"]);
                numConnectionTestInterval.Value = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["ConnectionTestInterval"]);
            }
            catch { }
        }

        /// <summary>
        /// This method is used to validate the settings data.
        /// </summary>
        /// <returns>Data valid or invalid (true/false)</returns>
        private bool IsValidData()
        {
            errProvider.Clear();

            if (txtClientName.Text.Trim().Length == 0)
            {
                errProvider.SetError(txtClientName, "Please provide client name");
                txtClientName.Focus();
                return false;
            }

            if (!Regex.Match(txtClientName.Text, "^[a-zA-Z0-9 ]+$").Success)
            {
                errProvider.SetError(txtClientName, "Client name must be alphanumeric");
                txtClientName.Focus();
                return false;
            }

            if (txtLoginName.Text.Trim().Length == 0)
            {
                errProvider.SetError(txtLoginName, "Please provide login name");
                txtLoginName.Focus();
                return false;
            }

            if (!Regex.Match(txtLoginName.Text, "^[a-zA-Z0-9 ]+$").Success)
            {
                errProvider.SetError(txtLoginName, "Login name must be alphanumeric");
                txtLoginName.Focus();
                return false;
            }

            if (txtPassword.Text.Trim().Length == 0)
            {
                errProvider.SetError(txtPassword, "Please provide password");
                txtPassword.Focus();
                return false;
            }

            if (txtPassword.Text.IndexOf(" ", 0) != -1)
            {
                errProvider.SetError(txtPassword, "Space is not allowed in password");
                txtPassword.Focus();
                return false;
            }

            string urlPattern = @"^(tcp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&amp;%\$\-]+)*@)"
            + "*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])"
            + @"\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)"
            + @"\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)"
            + @"\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|"
            + @"localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\."
            + @"(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)"
            + @"*(/($|[a-zA-Z0-9\.\,\?\'\\\+&amp;%\$#\=~_\-]+))*$";

            if (!Regex.Match(txtServerURI.Text, urlPattern).Success)
            {
                errProvider.SetError(txtServerURI, "Invalid server URI");
                txtServerURI.Focus();
                return false;
            }

            return true;
        }

        #endregion

        #region Form Control Events

        /// <summary>
        /// Occurs when Save button is clicked
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event Args</param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!IsValidData())
                {                    
                    return; // Return if invalid data, no need to save invalid settings
                }

                System.Configuration.Configuration config
                 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                config.AppSettings.Settings["ClientName"].Value = this.txtClientName.Text;
                config.AppSettings.Settings["LoginName"].Value = this.txtLoginName.Text;
                config.AppSettings.Settings["Password"].Value = this.txtPassword.Text;
                config.AppSettings.Settings["ServerURI"].Value = this.txtServerURI.Text;
                config.AppSettings.Settings["ServerPort"].Value = numConnectionPort.Value.ToString();
                config.AppSettings.Settings["ConnectionTestInterval"].Value = numConnectionTestInterval.Value.ToString();

                config.Save(ConfigurationSaveMode.Full);

                ConfigurationManager.RefreshSection("appSettings");

                this.Close();
            }
            catch { }
        }

        /// <summary>
        /// Occurs when Reload button is clicked
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event Args</param>
        private void btnReload_Click(object sender, EventArgs e)
        {
            try
            {
                LoadSettings(); 
            }
            catch { }
        }

        #endregion    
    }
}
